################################################################################################
####### Volha Charnysh. 2024. Uprooted: How post-WWII Population Transfers Remade Europe. CUP
####### Chapter 5: Plotting figures 5.3 and 5.4   #######
####### R version 3.6.3 (2020-02-29) -- "Holding the Windsock"
####### Platform: x86_64-apple-darwin15.6.0 (64-bit)
#######################################################
#######################################################

rm(list = ls())
library(ggplot2)  # for plot
library(plyr)     # for summarySE function
library(reshape2) # for converting from long to wide formata
library(knitr)    # for printing plot names 
library(openxlsx)


summarySE <- function(data=NULL, measurevar, groupvars=NULL, na.rm=FALSE,
                      conf.interval=.95, .drop=TRUE) {
  require(plyr)
  
  # New version of length which can handle NA's: if na.rm==T, don't count them
  length2 <- function (x, na.rm=FALSE) {
    if (na.rm) sum(!is.na(x))
    else       length(x)
  }
  
  # This does the summary. For each group's data frame, return a vector with
  # N, mean, and sd
  datac <- ddply(data, groupvars, .drop=.drop,
                 .fun = function(xx, col) {
                   c(N    = length2(xx[[col]], na.rm=na.rm),
                     mean = mean   (xx[[col]], na.rm=na.rm),
                     sd   = sd     (xx[[col]], na.rm=na.rm)
                   )
                 },
                 measurevar
  )
  
  # Rename the "mean" column    
  datac <- rename(datac, c("mean" = measurevar))
  
  datac$se <- datac$sd / sqrt(datac$N)  # Calculate standard error of the mean
  
  # Confidence interval multiplier for standard error
  # Calculate t-statistic for confidence interval: 
  # e.g., if conf.interval is .95, use .975 (above/below), and use df=N-1
  ciMult <- qt(conf.interval/2 + .5, datac$N-1)
  datac$ci <- datac$se * ciMult
  
  return(datac)
}


#########################################################
############ DIFFERENCES IN STATE CAPACITY ##############
#########################################################

adm<-read.csv("chapter5/AdminPub1988_.csv")
head(adm)

#reformat this dataset into long form
l <- reshape(adm, 
  varying = c("ShareAdm1988", "ShareAdm1980", "ShareAdm1983", "ShareAdm1985"), 
  v.names = "AdminPer1000",
  timevar = "year", 
  times = c("ShareAdm1988", "ShareAdm1980", "ShareAdm1983", "ShareAdm1985"), 
  direction = "long")


l$year[l$year=="ShareAdm1988"]<-1988
l$year[l$year=="ShareAdm1980"]<-1980
l$year[l$year=="ShareAdm1983"]<-1983
l$year[l$year=="ShareAdm1985"]<-1985

l.sort <- l[order(l$Woj., l$year),]
l.sort[1:10,]



##Type
admSum <- summarySE(l.sort, measurevar="AdminPer1000", groupvars=c("year", "Type")) #Resettled replaced w/ Type
admSum$Type<-factor(admSum$Type) #Suwalskie (ZZ, RUS) falls out
pd <- position_dodge(0.1) # move them .05 to the left and right


admSum<-subset(admSum, Type %in% c("ZZ", "PRUS"))


Figure5.3<- 
ggplot(admSum, aes(x=year, y=AdminPer1000, fill=Type)) + 
  geom_bar(position=position_dodge(), stat="identity",
           colour="black", # Use black outlines,
           size=.3) +      # Thinner lines
  geom_errorbar(aes(ymin=AdminPer1000-ci, ymax=AdminPer1000+ci),
                size=.3,    # Thinner lines
                width=.2,
                position=position_dodge(.9)) +
  xlab("year") +
  ylab("State administration (per 1000 people)") +
  scale_fill_hue(name="Legend", # Legend label, use darker colors
                 breaks=c("ZZ", "PRUS"),
                 labels=c("Resettled (N=11)", "Non-Resettled (N=6)")) +
  ggtitle("Average administrative capacity at the province level") +
  scale_y_continuous(breaks=0:20*4) +
  theme_bw()


Figure5.3

#################################################################
####### Figure 5.4: Differences in land and farm ownership ######
#################################################################

econ<-read.xlsx("chapter5/State_EconomyWoj.xlsx")
#reformat this dataset into long form
l <- reshape(econ, 
  varying = c("IndivLandOwn", "StateLandOwn", "IndivFarmOwn", "CoopFarmOwn", "StateFarmOwn"), 
  v.names = "value",
  timevar = "category", 
  times = c("IndivLandOwn", "StateLandOwn", "IndivFarmOwn", "CoopFarmOwn", "StateFarmOwn"), 
  direction = "long")


l$category[l$category =="IndivFarmOwn"]<-"Individual farms"
l$category[l$category =="StateFarmOwn"]<-"State farms"
l$category[l$category =="CoopFarmOwn"]<-"Cooperative farms"
l$category[l$category=="IndivLandOwn"]<-"Private land"
l$category[l$category=="StateLandOwn"]<-"State land"


l$Partition[l$Partition %in% c("AUS", "RUS")]<-"Other"
l$Partition[l$Partition %in% c("ZZ_PRUS")]<-"ZZ"

##Type
econSum <- summarySE(l, measurevar="value", groupvars=c("category", "Partition")) #Resettled replaced w/ Type
econSum$Partition <-factor(econSum$Partition) #Gdanskie falls out bc it is both. 
pd <- position_dodge(0.1) # move them .05 to the left and right

#Order as follows: 
#Land first,farms second 

econSum<-econSum[c(7:9, 13:15, 4:6,10:12,1:3), ]
econSum$category <- factor(econSum$category, levels = unique(econSum$category)) #unique is important here for reordering

Figure5.4<-ggplot(econSum, aes(x=category, y=value, fill=Partition)) + 
  geom_bar(position=position_dodge(), stat="identity",
           colour="black", # Use black outlines,
           size=.3) +      # Thinner lines
  geom_errorbar(aes(ymin=value-ci, ymax=value+ci),
                size=.3,    # Thinner lines
                width=.2,
                position=position_dodge(.9)) +
 xlab("") +
  ylab("Percentages for each category") +
  scale_fill_hue(name="Legend", # Legend label, use darker colors
                 breaks=c("ZZ", "PRUS", "Other"),
                 labels=c("Resettled (N=7)", "Non-Resettled Prussia (N=2)", "Non-Resettled Other (N=8)")) +
  ggtitle("Land and farm ownership by province in 1955") +
  scale_y_continuous(breaks=0:20*4) +
  theme_bw()

Figure5.4
